<template>
  <div>
    <template>
      <div class="ccui-app-container">
        <div class="ccui-advanced-search-wrapper ccui-clearfix">
          <el-search
            ref="search"
            :formProp="formData"
            @search="search"
            @change="change"
            :isShowSearch="isShowSearch"
            class="ccui-highsearch"
            :selectClear="true"
          >
            <!-- tab-->
            <div class="ccui-tab-wrapper">
              <el-button
                :type="isActive === index ? 'table-top-active' : 'table-top'"
                size="mini"
                v-for="(item, index) in focuses"
                :key="'tab' + index"
                @click="tabChange(item.focus)"
              >
                <template v-if="item.focus === 'all-item'"
                  >全部 ({{ totalNum }})</template
                >
                <template v-else-if="item.focus === 'un-closed'"
                  >待关闭</template
                >
                <template v-else-if="item.focus === 'under-closed'"
                  >关闭中</template
                >
                <template v-else-if="item.focus === 'return-closed'"
                  >关闭退回</template
                >
              </el-button>
            </div>
            <template slot="search">
              <!--              （2）支持按合同编号、合同名称、订单编号、订单名称、供应商、分类名称、订单发出时间、订单状态进行搜索。-->
              <el-input
                v-model="formData.orderName"
                clearable
                searchLabel="订单名称"
                placeholder="请输入订单名称模糊查询"
                @blur="handleTrim('orderName')"
              ></el-input>
              <el-input
                v-model="formData.orderNoAccurate"
                clearable
                searchLabel="订单编号"
                placeholder="请输入单据编号模糊查询"
              ></el-input>
              <el-input
                v-model="formData.contractCodeAccurate"
                clearable
                searchLabel="合同编号"
                placeholder="请输入合同编号模糊查询"
              ></el-input>
              <el-input
                v-model="formData.contractName"
                clearable
                searchLabel="合同名称"
                placeholder="请输入合同名称模糊查询"
                @blur="handleTrim('contractName')"
              ></el-input>

              <el-input
                v-model="formData.partyBName"
                clearable
                searchLabel="供货商"
                placeholder="请输入供货商模糊查询"
              ></el-input>
              <el-input
                v-model="formData.thirdCategoriesOfName"
                clearable
                searchLabel="分类名称"
                placeholder="请输入分类名称模糊查询"
                @blur="handleTrim('thirdCategoriesOfName')"
              ></el-input>
              <el-date-picker
                searchLabel="订单发出时间"
                v-model="formData.orderDeliveryTime"
                :clearable="false"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
              >
              </el-date-picker>
              <el-select
                v-model="formData.bizStatus"
                searchLabel="订单状态"
                placeholder="请选择订单状态查询"
              >
                <el-option label="审批通过" value="1"></el-option>
                <el-option label="待接收" value="2"></el-option>
                <el-option label="已接收" value="3"></el-option>
                <el-option label="已发货" value="4"></el-option>
                <el-option label="已撤回" value="5"></el-option>
                <el-option label="关闭中" value="6"></el-option>
                <el-option label="关闭退回" value="7"></el-option>
              </el-select>
            </template>
            <!-- 表单高级搜索 -->
            <el-input
              v-model="formData.orderName"
              clearable
              searchLabel="订单名称"
              placeholder="请输入订单名称模糊查询"
              @blur="handleTrim('orderName')"
              slot="searchItem1"
            ></el-input>
            <el-input
              v-model="formData.orderNoAccurate"
              clearable
              searchLabel="订单编号"
              placeholder="请输入单据编号模糊查询"
              slot="searchItem2"
            ></el-input>
            <el-input
              v-model="formData.contractCodeAccurate"
              clearable
              searchLabel="合同编号"
              placeholder="请输入合同编号模糊查询"
              slot="searchItem3"
            ></el-input>
            <el-input
              v-model="formData.contractName"
              clearable
              searchLabel="合同名称"
              placeholder="请输入合同名称模糊查询"
              @blur="handleTrim('contractName')"
              slot="searchItem4"
            ></el-input>
            <el-input
              v-model="formData.partyBName"
              clearable
              searchLabel="供货商"
              placeholder="请输入供货商模糊查询"
              slot="searchItem5"
            ></el-input>
            <el-input
              v-model="formData.thirdCategoriesOfName"
              clearable
              searchLabel="分类名称"
              placeholder="请输入分类名称模糊查询"
              slot="searchItem6"
              @blur="handleTrim('thirdCategoriesOfName')"
            ></el-input>
            <el-date-picker
              searchLabel="订单发出时间"
              v-model="formData.orderDeliveryTime"
              :clearable="false"
              align="right"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              slot="searchItem7"
              value-format="timestamp"
            >
            </el-date-picker>
            <el-select
              v-model="formData.bizStatus"
              slot="searchItem8"
              placeholder="请选择订单状态查询"
              searchLabel="订单状态"
            >
              <el-option label="审批通过" value="1"></el-option>
              <el-option label="待接收" value="2"></el-option>
              <el-option label="已接收" value="3"></el-option>
              <el-option label="已发货" value="4"></el-option>
              <el-option label="已撤回" value="5"></el-option>
              <el-option label="关闭中" value="6"></el-option>
              <el-option label="关闭退回" value="7"></el-option>
            </el-select>
          </el-search>
        </div>
        <!-- 表格 -->
        <div class="ccui-multifunctional-table-wrapper">
          <el-table
            ref="multipleTable"
            :data="tableData"
            :fit="true"
            :cell-style="cellStyle"
            border
            class="ccui-multifunctional-table"
            v-if="draggFlag"
            @cell-click="cellClick"
          >
            >
            <el-table-column
              :show-overflow-tooltip="true"
              label="序号"
              type="index"
              fixed
              width="50px"
            />
            <template v-for="(table, index) in tableTheadOptions">
              <el-table-column
                :fixed="table.fixed || false"
                :key="index"
                :type="table.type"
                :label="table.label"
                :align="table.align || 'left'"
                :header-align="table.headerAlign || 'left'"
                :min-width="table.width"
                :prop="table.prop"
                :show-overflow-tooltip="true"
                border="true"
              >
                <template slot-scope="scope">
                  {{ scope.row[table.prop] }}
                </template>
              </el-table-column>
            </template>
            <el-table-column label="操作" width="50" fixed="right">
              <template slot-scope="scope">
                <div v-if="scope.row.bizStatusName === '关闭中'">
                  <el-button
                    v-if="true"
                    size="mini"
                    type="text"
                    @click="handleReCall(scope.$index, scope.row)"
                    >撤回</el-button
                  >
                </div>
                <div v-else>
                  <el-button
                    v-if="true"
                    size="mini"
                    type="text"
                    @click="handleGoDetail(scope.row)"
                    >关闭</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <div class="ccui-table-footer" v-show="isShowPagination">
            <div id="ccui-paging">
              <el-pagination
                :total="totalNum"
                :page-size="pageSizeCode"
                background
                :current-page="pageNoCode"
                :page-sizes="[10, 20, 50, 100, 200, 500]"
                layout="total, sizes, prev, pager, next, jumper"
                popper-class="ccui-paging-page-size-popper"
                @prev-click="handlePrev"
                @next-click="handleNext"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <el-button
                class="ccui-pagination-btn"
                size="mini"
                type="default"
                @click="handleSizeChange('none')"
                >确定</el-button
              >
            </div>
          </div>
        </div>
        <!-- 表格end -->
      </div>
    </template>
  </div>
</template>

<script>
import {
  setSessionItem,
  getSessionItem,
  removeSessionItem,
  ishasAgentId
} from "@/basa/utils";
import getPower from "@/basa/utils/getPower.js";
import { closeRevokeApproval, listPageOrder } from "../api/index";
// import { clearComma } from "@/basa/utils";
import { formatNumber } from "@/basa/utils";
export default {
  name: "all-item",
  mixins: [getPower],
  inject: ["reload"],
  data() {
    return {
      isActive: 0,
      isShowDetail: true,
      isShowEdit: true,
      multiDataToEnd: {},
      singleDataToEnd: {},
      // 表格相关
      tableData: [], // 表格数据
      draggFlag: true,
      tableName: this.tableList.orderClose, // 表格命名
      tableThead: [], // 表格数据
      // 动态表格
      tableTheadOptions: [
        { label: "订单编号", prop: "orderNo", width: "130", fixed: true },
        { label: "订单名称", prop: "orderName", width: "300" },
        { label: "合同编号", prop: "contractCode", width: "130" },
        { label: "合同名称", prop: "contractName", width: "300" },
        {
          label: "供应商",
          prop: "partyBName",
          width: "200"
        },
        { label: "分类名称", prop: "thirdCategoriesOfName", width: "130" },
        {
          label: "订单数量",
          prop: "orderQuantity",
          width: "140"
        },
        {
          label: "发货数量",
          prop: "shipmentsNum",
          width: "140"
        },
        {
          label: "验收数量",
          prop: "acceptanceNum",
          width: "140"
        },
        // 前端计算 在途数量=已发货数量的合计-已验收数量的合计
        // { label: "在途数量", prop: "onWayNum" },
        { label: "订单发出时间", prop: "orderDeliveryTime", width: "100" },
        { label: "订单状态", prop: "bizStatusName", width: "70" },
        { label: "关闭原因", prop: "closeReason", width: "80" }
      ],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      focuses: [
        { focus: "all-item" },
        { focus: "un-closed" },
        { focus: "under-closed" },
        { focus: "return-closed" }
      ],
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        contractCodeAccurate: "",
        contractName: "",
        orderDeliveryTime: [],
        orderName: "",
        orderNoAccurate: "",
        partyBName: "",
        thirdCategoriesOfName: "",
        bizStatus: ""
      }, // 高级搜索提交数据
      formDataSearch: "",
      localSearchData: {},
      isShowSearch: true,
      isShow: false,
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: this.getLocalPageNo(),
      pageSizeCode: 10, //单页数据量
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "您确定要删除吗？",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",
      // 表格数据相关处理
      formatterList: {
        processStatusHandler(row, col) {
          switch (row.contractStatus) {
            case "1":
              return "待提交";
            case "2":
              return "审批中";
            case "3":
              return "已撤回";
            case "4":
              return "审批通过";
            case "5":
              return "审批退回";
            case "6":
              return "审批不通过";
          }
        },

        contractStatusHandler(row, col) {
          switch (row.contractStatus) {
            case "1":
              return "待提交";
            case "2":
              return "审批中";
            case "3":
              return "已撤回";
            case "4":
              return "审批通过";
            case "5":
              return "审批退回";
            case "6":
              return "审批不通过";
          }
        },

        isCreated: false
      },
      // 表格数据相关处理 end
      form: {}
    };
  },
  computed: {},
  watch: {},
  methods: {
    // 表格复选框能否选中
    selectEnable(row, rowIndex) {
      // 已撤回的不能选
    },
    // 单元格点击
    cellClick(row, column) {
      // console.log("单元格点击", row, column);
      if (column.label === "订单编号") {
        this.handleGoDetail(row);
      }
    },
    // 撤回
    handleReCall(index, row) {
      //调用撤回方法

      let obj = {};
      obj.id = row.id;
      closeRevokeApproval(obj)
        .then(res => {
          // console.log(res);
          let { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
          } else {
            this.$showErrorMessage(message);
          }
          // this.$message({
          //   message: "撤回成功",
          //   type: "success",
          //   duration: 2000,
          //   ccuiCustom: true
          // });
          this.getList();
        })
        .catch(e => {
          console.log(e);
        });
    },
    // 查看
    handleGoDetail(row) {
      if (row.bizStatusName === "关闭中" || row.bizStatusName === "关闭退回") {
        this.$router.push({
          path: `/orderManagement/close/approving-detail/${row.id}`
          // query: {
          //   type: 1
          // }
        });
      } else {
        this.$router.push({
          path: `/orderManagement/close/item-detail/${row.id}`,
          query: {
            type: 1
          }
        });
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (["orderNo"].includes(column.property)) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom",
        closeOnClickModal: false
      }).then(() => {
        this.$loading({
          lock: true,
          text: "删除中,请稍后...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
      });
    },
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    initData() {
      this.isShow = false;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    tabChange(data) {
      this.$router.push({ name: `orderManagement-List-close-${data}` });
    },
    // 上一页
    handlePrev() {
      console.log("上一页");
    },
    // 下一页
    handleNext() {
      console.log("下一页");
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      // let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      // setSessionItem("pageNo", this.tableName, {
      //   pageNo: val,
      //   searchForm: searchFormData.searchForm || {}
      // });
      // this.formDataSearch = {
      //   ...this.formDataSearch,
      //   ...searchFormData.searchForm
      // };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      // console.log('改变页面大小',this.formDataSearch);
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      if (this.formDataSearch.orderDeliveryTime) {
        this.formDataSearch.orderDeliveryTimeBegin = this.formDataSearch.orderDeliveryTime[0];
        this.formDataSearch.orderDeliveryTimeEnd =
          this.formDataSearch.orderDeliveryTime[1] + 86400000;
      }
      if (this.formDataSearch.bizStatus !== undefined) {
        switch (this.formDataSearch.bizStatus) {
          case "1":
            this.formDataSearch.bizStatus = 5;
            break;
          case "2":
            this.formDataSearch.bizStatus = 5;
            this.formDataSearch.isReceive = 0;
            this.formDataSearch.isShipments = 0;
            break;
          case "3":
            this.formDataSearch.bizStatus = 5;
            this.formDataSearch.isReceive = 1;
            this.formDataSearch.isShipments = 0;
            break;
          case "4":
            this.formDataSearch.bizStatus = 5;
            this.formDataSearch.isShipments = 1;
            break;
          case "5":
            this.formDataSearch.bizStatus = 52;
            break;
          case "6":
            this.formDataSearch.bizStatus = 53;
            break;
          case "7":
            this.formDataSearch.bizStatus = 54;
            break;
        }
      }
      this.getList(this.formDataSearch);
    },
    // 高级搜索 end
    change(val) {
      // console.log(val);
      this.formData = {
        contractCodeAccurate: "",
        contractName: "",
        orderDeliveryTime: [],
        orderName: "",
        orderNoAccurate: "",
        partyBName: "",
        thirdCategoriesOfName: "",
        bizStatus: ""
      };
    },
    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.permissionsType = 1;
      // obj.isShowPageLoading = true;
      if (!obj.bizStatus) {
        obj.listQueryType = 2;
      }
      listPageOrder(obj)
        .then(res => {
          if (res.data.data.rows.length === 0 && this.pageNoCode > 1) {
            this.pageNoCode--; //自减一页
            //重新自调用接口
            this.getList();
            return;
          }

          this.isShowPagination = res.data.data.recordsTotal > 0; //
          this.tableData = res.data.data.rows; //数据
          this.tableData.map(x => {
            if (x.bizStatus === "55") {
              x.bizStatusName = "已关闭";
            } else if (
              x.bizStatus === "5" &&
              x.isReceive === "1" &&
              x.isShipments === "1"
            ) {
              x.bizStatusName = "已发货";
            } else if (
              x.bizStatus === "5" &&
              x.isReceive === "0" &&
              x.isShipments === "1"
            ) {
              x.bizStatusName = "已发货";
            } else if (
              x.bizStatus === "5" &&
              x.isReceive === "0" &&
              x.isShipments === "0"
            ) {
              x.bizStatusName = "待接收";
            } else if (
              x.bizStatus === "5" &&
              x.isReceive === "1" &&
              x.isShipments === "0"
            ) {
              x.bizStatusName = "已接收";
            } else if (x.bizStatus === "5") {
              x.bizStatusName = "审批通过";
            } else if (x.bizStatus === "53") {
              x.bizStatusName = "关闭中";
            } else if (x.bizStatus === "54") {
              x.bizStatusName = "关闭退回";
            } else if (x.bizStatus === "52") {
              x.bizStatusName = "已撤回";
            }
            x.shipmentsNum = formatNumber(x.shipmentsNum, 3);
            x.orderQuantity = formatNumber(x.orderQuantity, 3);
            x.acceptanceNum = formatNumber(x.acceptanceNum, 3);
            x.onWayNum = x.shipmentsNum - x.acceptanceNum;

            if (x.orderDeliveryTime) {
              x.orderDeliveryTime = x.orderDeliveryTime.substring(0, 10);
            }
            return x;
          });
          this.totalNum = res.data.data.recordsTotal; //总记录条数
          this.total = res.data.data.total; //总页数
          this.pageNoCode = res.data.data.pageNo; // 当前页
        })
        .catch(e => {
          // console.log(e);
        });
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      const arr = [];
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
          arr.push(row.id);
        });
        this.idArrSelected = arr;
      }
    },
    // 排序
    sortChange(params) {
      this.sortord = params.order;
      this.sortprop = params.prop;
      this.getList();
    },
    // 默认显示多少条
    getLocalPageSize() {
      return getSessionItem("pageSize", this.tableList.orderClose) || 10;
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem("pageNo", this.tableList.orderClose);
      return (localData && localData.pageNo) || 1;
    }
  },
  created() {},
  mounted() {
    this.initData();
  },
  beforeRouteLeave(to, from, next) {
    removeSessionItem("pageNo");
    for (var key in this.$vnode.parent.componentInstance.cache) {
      delete this.$vnode.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    // for (let key in this.$vnode.parent.parent.componentInstance.cache) {
    //   delete this.$vnode.parent.parent.componentInstance.cache[
    //           ishasAgentId(to.path, key)
    //           ];
    // }
    // this.reload();
    next();
  },
  activated() {
    // if (Object.keys(this.localSearchData).length > 0) {
    //   setSessionItem("pageNo", this.tableName, {
    //     pageNo: this.pageNoCode,
    //     searchForm: this.localSearchData
    //   });
    // }
    // let localData = getSessionItem("pageNo", this.tableList.orderClose);
    // let data = localData && localData.searchForm;
    this.pageSizeCode = 10;
    this.pageNoCode = 1;
    this.change();
    this.$refs.search.handleChange(0);
    this.formDataSearch = {};
    this.getList({ ...this.formDataSearch });
    this.getList({ listQueryType: 2 });
  }
};
</script>

<style lang="scss" scoped>
/deep/.el-radio-group {
  width: 100px;
  font-size: 0;
}
/deep/.el-radio {
  color: #4a4a4a;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  outline: 0;
  margin-right: 30px;
  line-height: 2;
  padding-top: 4px;
  padding-left: 10px;
}
/deep/.el-form {
  margin-bottom: 0;
}

/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  width: 110px !important;
}
/*/deep/ .ccui-multifunctional-table-wrapper .el-table__fixed,*/
/*.ccui-multifunctional-table-wrapper .el-table__fixed-right {*/
/*  border: 0;*/
/*  height: 100% !important;*/
/*}*/
/*/deep/ .el-table__body-wrapper {*/
/*  z-index: 1;*/
/*}*/
/deep/ .el-searchs-box {
  width: 406px !important;
}
</style>
